var WebSocketServer = require('ws').Server,
    wss = new WebSocketServer({ port: 8181 });
var WebSocketClient = require('ws')
var axios = require("axios")
var qs = require("qs")
let interval

wss.on('connection', function (ws) {
    console.log('client connected');
    firstConnect()

    async function getToken() {
        return new Promise((resolve, reject) => {
        
            axios.post(`https://h5.kiwik.cn/restapi/auth/tokens`, qs.stringify(
                data
            ),
                {
                    headers: {
                        "x-kiwik-client-id": "igxknDUbISY3XAcBYJT9SIegd31sPu7B"
                    }
                }).then(res => {
                    resolve(res.data.access_token)
                }).catch(err => {
                    reject(err)
                })
        })


    }

    function connectWS(token) {
        var sock = new WebSocketClient(`wss://wsapi.kiwiot.com/?access_token=${token}`);
        sock.on("open", function () {
            console.log("connect success !!!!");
        });

        sock.on("message", function (data) {
            console.log(JSON.parse(data));
            ws.send(JSON.stringify(JSON.parse(data)))
        });

        sock.on("close", function () {
            console.log("close");
            firstConnect()
        });


        sock.on("error", function (err) {
            console.log("error: ", err);
            firstConnect()
        });

        interval = setInterval(()=>{
            var ss = {"header":{"namespace":"Iot.Application","name":"Ping","messageId":"a8c79691-0b6f-4bb1-85f1-9852dd0c5b3e","payloadVersion":1}}
            sock.send(JSON.stringify(ss))
        },40000)
    }

    async function firstConnect() {
        clearInterval(interval)
        let token = await getToken()
        console.log(token)
        connectWS(token)
    }

});

